package com.example.baselibs.net;

import android.util.Log;

import com.example.baselibs.BaseApplication;
import com.example.baselibs.net.interceptor.ResponseInterceptor;
import com.example.baselibs.net.interceptor.TokenInterceptor;
import com.example.baselibs.utils.JsonFormatUtils;
import com.franmontiel.persistentcookiejar.ClearableCookieJar;
import com.franmontiel.persistentcookiejar.PersistentCookieJar;
import com.franmontiel.persistentcookiejar.cache.SetCookieCache;
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import com.orhanobut.logger.Logger;

import org.jetbrains.annotations.NotNull;


import java.util.concurrent.TimeUnit;

import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class RetrofitManager {
    private static RetrofitManager instance;
    private OkHttpClient client;
    public static RetrofitManager getInstance(){
        if (instance==null){
            synchronized (RetrofitManager.class){
                if (instance==null){
                    instance=new RetrofitManager();
                }
            }
        }
        return instance;
    }

    public RetrofitManager(){

    }

    private OkHttpClient.Builder getClient(){
        return new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(getLogger());
    }

    private Retrofit.Builder getRetrofit(){
        return new Retrofit.Builder()
                .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.newThread()));
    }

    //PLC接口
    public <T> T getPLCApiService(Class<T> clz){
        //Okhttp3
        client=getClient().build();

        return getRetrofit().baseUrl(NetConstant.PLC_BASE_URL)
                .client(client)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build()
                .create(clz);

    }
    //自家用户数据库服务器接口
    public <T> T getUserApiService(Class<T> clz){
        ClearableCookieJar cookieJar=new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(BaseApplication.getContext()));

        client=getClient()
                .addInterceptor(new ResponseInterceptor())
                .addInterceptor(new TokenInterceptor())
                .cookieJar(cookieJar)
                .build();
        return getRetrofit().baseUrl(NetConstant.USER_BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(clz);
    }

    private HttpLoggingInterceptor getLogger(){
        //网络请求拦截信息
        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            private StringBuilder msg=new StringBuilder();
            @Override
            public void log(@NotNull String s) {
                Log.i("Okhttp",s);
                // 请求或者响应开始
                if (s.startsWith("--> POST")) {
                    msg.setLength(0);
                }
                // 以{}或者[]形式的说明是响应结果的json数据，需要进行格式化
                if ((s.startsWith("{") && s.endsWith("}"))
                        || (s.startsWith("[") && s.endsWith("]"))) {
                    s = JsonFormatUtils.formatJson(JsonFormatUtils.decodeUnicode(s));
                }
                msg.append(s.concat("\n"));
                // 响应结束，打印整条日志
                if (s.startsWith("<-- END HTTP")) {
                    Logger.e(msg.toString());
                }
            }
        });
        loggingInterceptor.level(HttpLoggingInterceptor.Level.BODY);
        return loggingInterceptor;
    }

}
